package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.web.admin.service.FileService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
//        获取原始文件名
        String fileName = file.getOriginalFilename();

//        创建新的文件名
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        fileName = simpleDateFormat.format(new Date()) + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "_" + fileName;


        InputStream inputStream = file.getInputStream();

        // 上传文件到 MinIO
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(inputStream, file.getSize(), -1) // -1 表示未知大小
                .contentType(file.getContentType())
                .build());

//        return fileName; // 返回文件名

//        返回文件url
//        return  endpoint + "/" + bucketName + "/" + fileName;
        return  String.join("/", endpoint, bucketName, fileName);
    }


    @Override
    public InputStream downloadFile(String fileName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build());
    }

    @Override
    public void deleteFile(String fileName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build());
    }
}
